#pragma once
#include<iostream>
#include<sys/socket.h>
#include<sys/types.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<cstring>
#include<unistd.h>


class udp_client
{
  private:
    int sockfd;
    std::string sever_ip;
    int sever_port;
  public:
    udp_client(std::string _ip,int _port)
      :sever_ip(_ip)
      ,sever_port(_port)
      {}
    bool initclient()
    {
      sockfd=socket(AF_INET,SOCK_DGRAM,0);
      if(sockfd<0)
      {
        std::cout<<"socket error"<<std::endl;
        return false;
      }
      std::cout<<"socket create success "<<sockfd<<std::endl;
      //客户端不需要绑定，需要自己的端口（sendto会产生自己的port端口）
      return true;
    }
    void start()
    {
      struct sockaddr_in peer;
      memset(&peer,0,sizeof(peer));
      peer.sin_family=AF_INET;
      peer.sin_port=htons(sever_port);
      peer.sin_addr.s_addr=inet_addr(sever_ip.c_str());

      std::string msg;
      for(;;)
      {
        std::cout<<"please enter#";
        std::cin>>msg;
        if(msg.size()>0)
        {
          sendto(sockfd,msg.c_str(),msg.size(),0,(struct sockaddr*)&peer,sizeof(peer));
        }
        else 
        {
          std::cout<<"请重新输入"<<std::endl;
        }
      }
    }
    ~udp_client()
    {
      if(sockfd>0)
      {
        close(sockfd);
      }
    }

};
